package be.rubengerits.bluetooth.tester.filepicker;

import java.io.File;
import be.rubengerits.bluetooth.tester.R;

import android.content.Context;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

public class FilePickerAdapter extends ArrayAdapter<File> {

	private static final String PARENT = "..";

	private static final String ROOT = Environment
			.getExternalStorageDirectory().getPath();

	private File mFileLocation;
	
	public FilePickerAdapter(Context context) {
		super(context, android.R.layout.simple_spinner_dropdown_item);
		construct();
	}

	public FilePickerAdapter(Context context, int resource,
			int textViewResourceId) {
		super(context, resource, textViewResourceId);
		construct();
	}

	public File getFileLocation() {
		return mFileLocation;
	}

	public void construct() {
		File rootFile = new File(ROOT);
		updatePosition(rootFile);
	}

	public void updatePosition(File selectedFile) {
		File[] listFiles = selectedFile.listFiles();

		mFileLocation = selectedFile;

		clear();
		if (selectedFile.getParentFile() != null) {
			add(selectedFile.getParentFile());
		}
		for (File f : listFiles) {
			if (!f.isHidden()) {
				add(f);
			}
		}
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = super.getView(position, convertView, parent);

		TextView textView = (TextView) view.findViewById(android.R.id.text1);

		File item = getItem(position);
		
		if (position == 0 && item.getAbsolutePath().equals(mFileLocation.getParent())) {
			textView.setText(PARENT);
		} else {
			textView.setText(item.getName());
		}

		if (item.isDirectory()) {
			textView.setCompoundDrawablesWithIntrinsicBounds(
				android.R.drawable.star_on, 0, 0, 0);
					
		} else {
			textView.setCompoundDrawablesWithIntrinsicBounds(
				android.R.drawable.star_off, 0, 0, 0);
		}

		return view;
	}
}
